package com.sunwayhorizo.health.business.patad.encounter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.base.BaseManager;
import com.sunwayhorizo.health.business.clinic.emr.document.InpatientRecordsManagerLocal;
import com.sunwayhorizo.health.business.clinic.emr.observation.ObservationManagerLocal;
import com.sunwayhorizo.health.business.dto.DictionaryDTO;
import com.sunwayhorizo.health.business.dto.PageDTO;
import com.sunwayhorizo.health.business.dto.ResultsDTO;
import com.sunwayhorizo.health.business.dto.clinic.emr.document.EmrDiagnosisDTO;
import com.sunwayhorizo.health.business.dto.patad.encounter.DischargedDTO;
import com.sunwayhorizo.health.business.dto.patad.encounter.PatientEncounterDTO;
import com.sunwayhorizo.health.business.patad.empi.PatientManagerLocal;
import com.sunwayhorizo.health.business.patad.empi.query.PatientQueryLocal;
import com.sunwayhorizo.health.business.patad.encounter.query.PatientEncounterQueryLocal;
import com.sunwayhorizo.health.business.registries.employee.query.EmployeeQueryLocal;
import com.sunwayhorizo.health.business.registries.organization.query.DepartmentQueryLocal;
import com.sunwayhorizo.health.business.registries.person.PersonManagerLocal;
import com.sunwayhorizo.health.business.registries.place.BedManagerLocal;
import com.sunwayhorizo.health.common.DataTypeUtil;
import com.sunwayhorizo.health.common.DateUtil;
import com.sunwayhorizo.health.common.Hl7NullRemover;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.common.ValidateUtilLocal;
import com.sunwayhorizo.health.common.validateGroups.NewDeptTransfer;
import com.sunwayhorizo.health.common.validateGroups.NewInHospital;
import com.sunwayhorizo.health.common.validateGroups.NewOutHospital;
import com.sunwayhorizo.health.common.validateGroups.ValidateCardNo;
import com.sunwayhorizo.health.ets.factory.DictionaryFactory;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.datatypes.CE;
import com.sunwayhorizo.health.hl7.datatypes.II;
import com.sunwayhorizo.health.hl7.persistent.RimCoreActCdSets;
import com.sunwayhorizo.health.hl7.persistent.RimCoreActIi;
import com.sunwayhorizo.health.hl7.persistent.RimCoreActPrtcptns;
import com.sunwayhorizo.health.hl7.persistent.RimCoreActRelations;
import com.sunwayhorizo.health.hl7.persistent.RimCoreEntyAddrParts;
import com.sunwayhorizo.health.hl7.persistent.RimCoreEntyAddrs;
import com.sunwayhorizo.health.hl7.rim.ActParticipation;
import com.sunwayhorizo.health.hl7.rim.ActRelationship;
import com.sunwayhorizo.health.hl7.rim.ControlAct;
import com.sunwayhorizo.health.hl7.rim.Employee;
import com.sunwayhorizo.health.hl7.rim.Observation;
import com.sunwayhorizo.health.hl7.rim.Organization;
import com.sunwayhorizo.health.hl7.rim.Patient;
import com.sunwayhorizo.health.hl7.rim.PatientEncounter;
import com.sunwayhorizo.health.hl7.rim.Person;
import com.sunwayhorizo.health.hl7.rim.Place;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.vocabulary.ActClass;
import com.sunwayhorizo.health.hl7.vocabulary.ActCode;
import com.sunwayhorizo.health.hl7.vocabulary.ActIICode;
import com.sunwayhorizo.health.hl7.vocabulary.ActMood;
import com.sunwayhorizo.health.hl7.vocabulary.ActRelationshipType;
import com.sunwayhorizo.health.hl7.vocabulary.ActStatus;
import com.sunwayhorizo.health.hl7.vocabulary.Direction;
import com.sunwayhorizo.health.hl7.vocabulary.EntityNameUse;
import com.sunwayhorizo.health.hl7.vocabulary.EntityStatus;
import com.sunwayhorizo.health.hl7.vocabulary.ParticipationType;
import com.sunwayhorizo.health.hl7.vocabulary.RoleClass;
import com.sunwayhorizo.health.hl7.vocabulary.RoleCode;
import com.sunwayhorizo.health.hl7.vocabulary.RoleIICode;

@Name("AdmitManager")
@Stateless
public class AdmitManager extends BaseManager implements AdmitManagerLocal
{
    private PatientManagerLocal patientManager = (PatientManagerLocal) Component.getInstance("PatientManager");
    private PatientEncounterQueryLocal patientEncounterQuery = (PatientEncounterQueryLocal) Component.getInstance("PatientEncounterQuery");
    private PatientQueryLocal patientQuery = (PatientQueryLocal) Component.getInstance("PatientQuery");
    private ValidateUtilLocal validateUtil = (ValidateUtilLocal) Component.getInstance("ValidateUtil");
    private EmployeeQueryLocal employeeQuery = (EmployeeQueryLocal) Component.getInstance("EmployeeQuery");
    private PatientEncounterCommonManagerLocal commonManager = (PatientEncounterCommonManagerLocal) Component
        .getInstance("PatientEncounterCommonManager");
    private PersonManagerLocal personManager = (PersonManagerLocal) Component.getInstance("PersonManager");
    private BedManagerLocal bedManager = (BedManagerLocal) Component.getInstance("BedManager");
    private ObservationManagerLocal observationManager = (ObservationManagerLocal) Component.getInstance("ObservationManager");
    private DepartmentQueryLocal departmentQuery = (DepartmentQueryLocal) Component.getInstance("DepartmentQuery");


    // 入院
    @Override
    public ResultsDTO newInHospital(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        ResultsDTO resultsDTO = validateInHospital(patientEncounterDTO);
        if (resultsDTO != null)
        {
            return resultsDTO;
        }
        // 入院动作
        PatientEncounter patientEncounter = constructInhospital(patientEncounterDTO);

        // 操作员
        // 首个参数为0代表此参数无效不使用
        Employee empRole = employeeQuery.findEmployeeByCode(patientEncounterDTO.getLoginBaseInfo().getOperateId());

        if (empRole == null)
        {
            empRole = employeeQuery.findEmployeeByCode("12345");
            log.info("操作员为空,使用默认操作员");
        }
        else
        {
            log.info("成功得到操作员角色！");
        }
        // 操作员参与动作
        ActParticipation empPart = getActFactory().newActParticipation();
        empPart.setTypeCode(ParticipationType.ADM);
        addParticipation(empRole, empPart);

        // 患者
        Patient patient = patientManager.findOrCreatePateint(patientEncounterDTO);
        if (patient == null)
        {
            log.info("入院患者为空");
            log.info("入院失败！");
            return this.getResultsDTO("入院失败", true, false);
        }
        // 患者参与动作
        ActParticipation patientPart = getActFactory().newActParticipation();
        patientPart.setTypeCode(ParticipationType.SBJ);
        // 设置就诊号、住院号
        setInhosEncounterId(patientEncounterDTO, patientPart, patient);
        addParticipation(patient, patientPart);

        // 科室
        Role workGroupRole = patientQuery.findRoleById(Long.valueOf(patientEncounterDTO.getInHospitalDTO().getRoleID()));
        if (workGroupRole == null)
        {
            log.info("部门为空！");
            log.info("入院失败！");
            return this.getResultsDTO("入院失败", true, false);
        }
        else
        {
            log.info("成功得到部门角色！");
        }
        // 科室参与动作
        ActParticipation workzGroupPart = getActFactory().newActParticipation();
        workzGroupPart.setTypeCode(ParticipationType.SDLOC);
        addParticipation(workGroupRole, workzGroupPart);

        // 诊断
        Observation ob = observationManager.newObservationNotPersist(constructEmrDiagnosisDTO(patientEncounterDTO));

        // 创建动作关联
        ActRelationship onRelation = getActFactory().newActRelationship();
        onRelation.setTypeCode(ActRelationshipType.COMP);
        addRelationship(ob, onRelation, Direction.SOURCE);

        ControlAct controlAct = newControlAct(patientEncounter);
        save(controlAct);

        PatientEncounter outHos = patientEncounterQuery.findLastAvtiveOutHos(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId());
        if (outHos != null)
        {
            commonManager.updatePateintEncounter(outHos, ActStatus.COMPLETED);
        }
        log.info("入院成功！");
        return this.getResultsDTO("入院登记成功", true, true);
    }


    // 转科
    @Override
    public ResultsDTO newDeptTransfer(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        ResultsDTO resultsDTO = validatePatientTransfer(patientEncounterDTO);
        if (resultsDTO != null)
        {
            return resultsDTO;
        }

        // 构建转科动作
        PatientEncounter patientEncounterAct = constructPatientTransfer(patientEncounterDTO);

        // 构造所有参与角色及参与关系
        resultsDTO = constructTransferPart(patientEncounterDTO);
        if (resultsDTO != null)
        {
            return resultsDTO;
        }

        ControlAct controlAct = newControlAct(patientEncounterAct);
        save(controlAct);
        // 上次活动的入科动作
        PatientEncounter lastIndepat = patientEncounterQuery.findLastAvtiveIndepartmentPatientEncounter(patientEncounterDTO.getPatientBaseInfoDTO()
            .getNatureId());
        // 上次活的接诊动作
        PatientEncounter lastRece = patientEncounterQuery.findLastAvtiveRecievingPatientEncounter(patientEncounterDTO.getPatientBaseInfoDTO()
            .getNatureId());

        commonManager.updatePateintEncounter(lastIndepat, ActStatus.COMPLETED);
        commonManager.updatePateintEncounter(lastRece, ActStatus.COMPLETED);
        // 床位
        Role bedRole = commonManager.findBedRole(patientEncounterDTO);
        if (bedRole == null)
        {
            log.info("ReceivingManager-newReceiving-床位为空!");
            return getResultsDTO("床位为空,请选择正确的床位", true, false);
        }
        bedManager.modifyBedStatus(bedRole, EntityStatus.EMPTYBED);

        log.info("转科成功");
        return this.getResultsDTO("转科成功", true, true);

    }


    /**
     * 此方法待补完，需加入费用检查、医嘱信息及其他业务需求相关联动作 目前只用于数据接口
     */
    @Override
    public ResultsDTO newOutHospital(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {

        ResultsDTO resultsDTO = validateOutHospital(patientEncounterDTO);
        if (resultsDTO != null)
        {
            return resultsDTO;
        }

        // 出院动作
        PatientEncounter patientEncounterAct = constructOutHospital(patientEncounterDTO);

        // 患者
        Patient patient = patientQuery.findPatientByNeturalId(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId());
        if (patient == null)
        {
            log.info("患者为空！");
            return this.getResultsDTO("出院失败", true, false);
        }
        ActParticipation patientPart = getActFactory().newActParticipation();
        patientPart.setTypeCode(ParticipationType.SBJ);
        addParticipation(patient, patientPart);

        // 工作组
        Role workGroupRole = departmentQuery.findWorkGroupRoleByWorkGroupCode(patientEncounterDTO.getDischargedDTO().getWorkgroupCode());
        if (workGroupRole == null)
        {
            log.info("部门为空！");
            return this.getResultsDTO("出院失败", true, false);
        }
        else
        {

            log.info("成功得到部门角色！");
        }
        // 科室参与动作
        ActParticipation workzGroupPart = getActFactory().newActParticipation();
        workzGroupPart.setTypeCode(ParticipationType.ORG);
        addParticipation(workGroupRole, workzGroupPart);

        // 出院操作员
        Employee empRole = employeeQuery.findEmployeeByCode(patientEncounterDTO.getLoginBaseInfo().getOperateId());
        if (empRole == null)
        {
            empRole = employeeQuery.findEmployeeByCode("12345");

            log.info("操作员为空,使用默认操作员");
        }
        else
        {
            log.info("成功得到操作员角色！");
        }
        ActParticipation empPart = getActFactory().newActParticipation();
        empPart.setTypeCode(ParticipationType.ADM);
        addParticipation(empRole, empPart);

        ControlAct controlAct = newControlAct(patientEncounterAct);
        save(controlAct);

        // 修改床位状态
        Role bedRole = commonManager.findBedRole(patientEncounterDTO);
        bedManager.modifyBedStatus(bedRole, EntityStatus.EMPTYBED);

        for (PatientEncounter pe : patientEncounterQuery.findAllActivePE(patientEncounterDTO.getEncounterID()))
        {
            commonManager.updatePateintEncounter(pe, ActStatus.COMPLETED);
        }

        log.info("出院成功");
        return this.getResultsDTO("出院成功", true, false);

    }


    // 入院待入科列表
    @Override
    public ResultsDTO findAdmitList(String workgroupId, String encounterType, PageDTO pageDTO) throws Hl7Exception
    {
        String info = null;
        em.clear();
        List<PatientEncounterDTO> patEncList = new ArrayList<PatientEncounterDTO>();
        List<PatientEncounter> list = null;
        if (ActCode.HOSPITALIZED.code().stringValue().equals(encounterType))
        {

            list = patientEncounterQuery.findAllActiveInhospital(workgroupId, pageDTO.getPageNo(), pageDTO.getPageSize());

            for (PatientEncounter act : list)
            {
                PatientEncounterDTO dto = convertPatientEncounterDTO(act);

                patEncList.add(dto);

                Hl7NullRemover.removeHl7Null(dto);
            }

            pageDTO.setTotalRecord((int) patientEncounterQuery.findCountAllActiveInhospital(workgroupId));

        }
        else if (ActCode.PATIENTTRANSFER.code().stringValue().equals(encounterType))
        {
            list = patientEncounterQuery.findAllActiveTransfer(workgroupId, pageDTO.getPageNo(), pageDTO.getPageSize());

            for (PatientEncounter act : list)
            {
                PatientEncounterDTO dto = new PatientEncounterDTO();
                convertTransferAndInhospital(act, dto);
                patEncList.add(dto);

                Hl7NullRemover.removeHl7Null(dto);
            }
            pageDTO.setTotalRecord((int) patientEncounterQuery.findCountAllActiveTransfer(workgroupId));
        }
        if (ListUtil.isEmpty(patEncList))
        {
            info = "该工作下没有要入科的患者";
            log.info("AdmitManager-findAdmitList:" + info);
            return this.getResultsDTO(info, true, null);
        }
        info = "AdmitManager-findAdmitList:" + "该工作组下有" + patEncList.size() + "个患者需要入科";
        log.info(info);

        return this.getResultsDTO(info, true, patEncList, pageDTO);
    }


    @Deprecated
    public ResultsDTO findPatientEncounterDTOByNatureId(String natureId) throws Hl7Exception
    {
        PatientEncounterDTO patientEncounterDto = findPatientEncounterDTOByPatientNatureId(natureId);
        if (null != patientEncounterDto)
            return this.getResultsDTO("患者基本信息查询成功", true, patientEncounterDto);
        else
            return this.getResultsDTO("患者基本信息为空", true, null);
    }


    public ResultsDTO validateCardNo(PatientEncounterDTO dto) throws Hl7Exception
    {

        ValidateUtilLocal util = (ValidateUtilLocal) Component.getInstance("ValidateUtil");
        if (util.verified(dto, ValidateCardNo.class))
        {
            if (patientQuery.validateEntityIIExsit(dto.getCardId(), dto.getCardTypeDic().getCodingschemeEnName(), dto.getCardTypeDic().getConceptCode()))
            {
                return getResultsDTO("身份证验证失败", true, false);
            }
            if (patientQuery.validateRoleIIExsit(dto.getMedicalCardId(), dto.getCardTypeDic().getCodingschemeEnName(), dto.getCardTypeDic()
                .getConceptCode()))
            {
                return getResultsDTO("医保号验证失败", true, false);
            }
        }

        return getResultsDTO("验证成功", true, true);

    }


    // 根据患者id查询患者宏元素信息
    @Override
    @Deprecated
    public PatientEncounterDTO findPatientEncounterDTOByPatientNatureId(String natureId) throws Hl7Exception
    {

        PatientEncounterDTO patientEncounterDTO = new PatientEncounterDTO();

        Patient patient = patientQuery.findPatientByNeturalId(natureId);
        if (null == patient)
        {
            log.info("AdmitManager-findPatientEncounterDTOByPatientNatureId-查询到患者为空！");
            return patientEncounterDTO;
        }
        Person person = (Person) patient.getPlayerEntities();

        patientEncounterDTO.setPatientBaseInfoDTO(personManager.constructorPatBaseInfo(person));
        patientEncounterDTO.getPatientBaseInfoDTO().setPersonId(patient.getRoleId().toString());

        patientEncounterDTO.getPatientBaseInfoDTO().setNatureId(natureId);
        if (!person.getEntyIiList().isEmpty())
        {
            log.info(person.getEntyIiList().get(0).getExtensionTxt());
            patientEncounterDTO.setCardId(person.getEntyIiList().get(0).getExtensionTxt());
        }
        // 住院号
        // patientEncounterDTO.getInHospitalDTO().setHospitalizationNO(patient.getPtHospitalizationNO().code().stringValue());

        // 住院次数
        // patientEncounterDTO.getInHospitalDTO().setEncounterNum(patient.getPtEncounterNo().code().stringValue());

        // 获取入院动作
        PatientEncounter inHosEncounter = patientEncounterQuery.findLastInhosActByEncounterId(natureId);

        patientEncounterDTO = convertBasePatientEncounterDTO(patientEncounterDTO, inHosEncounter);

        for (RimCoreActPrtcptns actPrtcptns : inHosEncounter.getParticipations())
        {
            ActParticipation actPrtcptn = (ActParticipation) actPrtcptns;
            if (actPrtcptn.getTypeCode().equals(ParticipationType.SDLOC))
            {
                if (actPrtcptn.getRoleparticipation().getClassCode().equals(RoleClass.PART))
                {
                    Role r = (Role) actPrtcptn.getRoleparticipation();
                    Organization org = (Organization) r.getPlayerEntities();
                    // 科室名称
                    patientEncounterDTO.getInHospitalDTO().setDeptName(org.getEntyNamesList().get(0).getFormatted());
                    patientEncounterDTO.getInHospitalDTO().setRoleID(r.getRoleId().toString());
                    // TODO 区域医疗时修改
                    patientEncounterDTO.getInHospitalDTO().setOrgName("大庆油田总医院");
                }
            }
        }

        // 入科相关信息
        for (RimCoreActRelations relation : inHosEncounter.getSourceActRelationsList())
        {
            ActRelationship relations = (ActRelationship) relation;
            log.info("AdmintManager-findPatientEncounterDTOByPatientNatureId-" + relations.getTypeCode().code().stringValue());
            log.info("AdmintManager-findPatientEncounterDTOByPatientNatureId-" + relations.getSourceAct().getCode().code().stringValue());

            if (relations.getTypeCode().equals(ActRelationshipType.SBS) && relations.getTargetAct().getClassCode().equals(ActClass.ENC)
                    && relations.getTargetAct().getCode().code().equals(ActCode.INDEPARTMENT.code()))
            {

                // 入科时间
                String admissionTime = "";
                if (((PatientEncounter) relation.getTargetAct()).getActivityTime() != null)
                {
                    admissionTime = ((PatientEncounter) relation.getTargetAct()).getActivityTime().hull().low().toDateString("yyyy-MM-dd HH:mm:ss");

                }
                patientEncounterDTO.getInDepartment().setAdmissionTime(admissionTime);

                // 床位号
                for (RimCoreActPrtcptns prt : relation.getTargetAct().getPrtcptnsActList())
                {
                    if (prt.getRoleparticipation().getClassCode().equals(RoleClass.IDENT)
                            && prt.getRoleparticipation().getCode().code().equals(RoleCode.BED.code()))
                    {
                        Role bedRole = (Role) prt.getRoleparticipation();

                        Place p = (Place) prt.getRoleparticipation().getPlayerEntities();

                        String bedNO = "";
                        // if(ListUtil.isNotEmpty(p.getEntyNamesList()))
                        // {
                        // for (RimCoreEntyNames rimCoreEntyNames :
                        // p.getEntyNamesList()) {
                        // if
                        // (rimCoreEntyNames.getEntyNameUsesList().get(0).getUse()
                        // .equals(BusinessConstants.USECODE_EN_LEGAL)) {
                        // rimCoreEntyNames.setFormatted(bedDTO.getBedNo());
                        // rimCoreEntyNames.getEntyNamePartsList().get(0).setLiteral(bedDTO.getBedNo());
                        // }
                        // }
                        // }
                        if (!p.getEntyNamesList().isEmpty())
                        {
                            bedNO = p.getEntyNamesList().get(0).getFormatted();
                        }
                        patientEncounterDTO.getInDepartment().setBedNO(bedNO);
                        // patientEncounterDTO.getInDepartment().setBedNO(
                        // p.getEntyNamesList().get(0).getFormatted());

                        patientEncounterDTO.getInDepartment().setBedRoleID(bedRole.getRoleId().toString());

                        for (RimCoreEntyAddrs addr : p.getEntyAddrsList())
                        {
                            for (RimCoreEntyAddrParts addrParts : addr.getEntyeAddrPartsList())
                            {
                                patientEncounterDTO.getInDepartment().setRoomNO(addrParts.getLiteral());
                            }
                        }

                    }
                }

                // 诊断名称
                for (RimCoreActCdSets cd : relation.getTargetAct().getActCdSetsList())
                {
                    if (cd.getCodingschemeEnName().equals("Diagnosis"))
                    {
                        // 对于DictionaryDTO的处理请参照框架处理方法，不要单独设置值来处理
                        patientEncounterDTO.getOutpat_diagose().setConceptName(cd.getConceptName());
                        patientEncounterDTO.getInHospitalDTO().getOutPatDiagnose().setConceptName(cd.getConceptName());
                    }
                }
            }
        }
        log.info("AdmintManager-findPatientEncounterDTOByPatientNatureId-" + inHosEncounter.getActId());
        Hl7NullRemover.removeHl7Null(patientEncounterDTO);
        return patientEncounterDTO;

    }


    // 根据病人生成住院号
    // add by Obama
    private String generalPtHospitalizationNO(Patient patient) throws Hl7Exception
    {

        if (ListUtil.isEmpty(patientManager.getInfoInsuranceDTOFromPatient(patient)))
        {
            // 没有医保卡
            return "20" + em.createNativeQuery("select SEQ_INHOSNO_INSURANCE.NEXTVAL from dual").getResultList().get(0).toString();
        }
        else
        {
            // 有医保卡(暂时不考虑哪些有卡还不用的人)
            return "10" + em.createNativeQuery("select SEQ_INHOSNO_INSURANCE.NEXTVAL from dual").getResultList().get(0).toString();
        }

    }


    // 生成门诊诊断dto
    private EmrDiagnosisDTO constructEmrDiagnosisDTO(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        EmrDiagnosisDTO dto = new EmrDiagnosisDTO();
        dto.getDiagnosisType().setCodingschemeChName("诊断类别");
        dto.getDiagnosisType().setCodingschemeEnName("DiagnosisType");
        dto.getDiagnosisType().setCodingschemeOid("DIAGNOSIS_TYPE");
        dto.getDiagnosisType().setConceptCode("1");
        dto.getDiagnosisType().setConceptName("门诊诊断");
        dto.getDiagnosisType().setVersionName("Version1.0");
        dto.setDiagnosisName(patientEncounterDTO.getInHospitalDTO().getOutPatDiagnose());

        Employee ee = null;
        if (StrUtil.isNotEmpty(patientEncounterDTO.getInHospitalDTO().getDoctorId()))
        {
            ee = employeeQuery.findEmployeeByCode(patientEncounterDTO.getInHospitalDTO().getDoctorId());
        }
        if (ee == null)
        {
            log.info("AdmitManager-constructEmrDiagnosisDTO-医生为空！");
            return dto;
        }
        dto.setEmpRoleId(ee.getRoleId().toString());
        return dto;
    }


    // 组装入院最基本信息
    private PatientEncounterDTO convertBasePatientEncounterDTO(PatientEncounterDTO patientEncounterDTO, PatientEncounter encounter) throws Hl7Exception
    {
        if (encounter == null)
        {
            System.out.println("encounter为空！");
            return patientEncounterDTO;
        }
        // 入院方式
        patientEncounterDTO.getInHospitalDTO().setAdmissionWay(
            encounter.getAdmissionWay() == null ? null : encounter.getAdmissionWay().code().literal().toString());
        // 入院目的
        patientEncounterDTO.getInHospitalDTO().setAdmissionPurpose(
            encounter.getAdmissionPurpose() == null ? null : encounter.getAdmissionPurpose().code().literal().toString());
        // 联系人
        patientEncounterDTO.getInHospitalDTO().setLinkMan(encounter.getPeLinkMan() == null ? null : encounter.getPeLinkMan().stringValue());

        // 联系方式
        patientEncounterDTO.getInHospitalDTO().setLinkManWay(encounter.getPeLinkManWay() == null ? null : encounter.getPeLinkManWay().stringValue());

        // 住院号
        for (RimCoreActIi cd : encounter.getActsIiList())
        {
            if (cd.getIdentifierName().equals(ActCode.HOSPITALIZED.code().stringValue()))
            {
                patientEncounterDTO.setEncounterID(cd.getExtensionTxt());
            }
        }

        // 费别
        for (RimCoreActCdSets cds : encounter.getActCdSetsList())
        {
            if (cds.getCodingschemeEnName() != null && cds.getCodingschemeEnName().equals("ChargeType"))
            {
                patientEncounterDTO.getChargeTypeDic().setCodingschemeChName(cds.getCodingschemeChName());
                patientEncounterDTO.getChargeTypeDic().setCodingschemeEnName(cds.getCodingschemeEnName());
                patientEncounterDTO.getChargeTypeDic().setConceptCode(cds.getConceptCode());
                patientEncounterDTO.getChargeTypeDic().setConceptName(cds.getConceptName());
                patientEncounterDTO.getChargeTypeDic().setCodingschemeOid(cds.getCodingschemeOid());

            }
        }

        // 入院时间
        if (encounter.getActivityTime() != null)
        {
            patientEncounterDTO.getInHospitalDTO().setAdmissionTime(encounter.getActivityTime().hull().low().toDateString("yyyy-MM-dd HH:mm:ss"));

        }
        else
        {
            patientEncounterDTO.getInHospitalDTO().setAdmissionTime(encounter.getCreationDate().toString());
        }
        Hl7NullRemover.removeHl7Null(patientEncounterDTO);
        return patientEncounterDTO;
    }


    // 组装入院PatientEncounterDTO
    @Override
    public PatientEncounterDTO convertPatientEncounterDTO(PatientEncounterDTO patientEncounterDTO, PatientEncounter encounter) throws Hl7Exception
    {
        if (encounter == null)
        {
            log.info("AdmitManager-convertPatientEncounterDTO-encounter为空！");
            return patientEncounterDTO;
        }

        // 入院方式
        patientEncounterDTO.getInHospitalDTO().setAdmissionWay(
            encounter.getAdmissionWay() == null ? null : encounter.getAdmissionWay().code().literal().toString());
        // 入院目的
        patientEncounterDTO.getInHospitalDTO().setAdmissionPurpose(
            encounter.getAdmissionPurpose() == null ? null : encounter.getAdmissionWay().code().literal().toString());
        // 联系人
        patientEncounterDTO.getInHospitalDTO().setLinkMan(encounter.getPeLinkMan() == null ? null : encounter.getPeLinkMan().stringValue());
        // 联系方式
        patientEncounterDTO.getInHospitalDTO().setLinkManWay(encounter.getPeLinkManWay() == null ? null : encounter.getPeLinkManWay().stringValue());
        // 就诊号
        if (encounter.getId(ActIICode.HOSPITALIZED) != null && encounter.getId(ActIICode.HOSPITALIZED).clinicNo() != null)
        {
            patientEncounterDTO.setEncounterID(encounter.getId(ActIICode.HOSPITALIZED).clinicNo().stringValue());
        }
        // 费别
        patientEncounterDTO.setChargeTypeDic(getDictionaryFactory().getDictionaryDTOByCe(encounter.getChargeType()));

        // 入院时间
        if (encounter.getActivityTime() != null)
        {
            patientEncounterDTO.getInHospitalDTO().setAdmissionTime(encounter.getActivityTime().hull().low().toDateString("yyyy-MM-dd HH:mm:ss"));
        }
        for (ActParticipation actPrtcptn : encounter.getParticipations())
        {

            if (actPrtcptn.getTypecode().equals(ParticipationType.SBJ))
            {
                if (actPrtcptn.getRoleparticipation().getCode().code().equals(RoleCode.PATIENT.code()))
                {
                    Patient patient = (Patient) actPrtcptn.getRoleparticipation();

                    // 患者信息
                    commonManager.convertByPatient(patientEncounterDTO, patient);
                    // 住院次数
                    if (actPrtcptn.getSequenceNumber() != null && actPrtcptn.getSequenceNumber().intValue() != 0)
                    {
                        patientEncounterDTO.getInHospitalDTO().setEncounterNum(actPrtcptn.getSequenceNumber().intValue() + "");

                    }
                    else
                    {
                        patientEncounterDTO.getInHospitalDTO().setEncounterNum("1");
                    }
                    continue;
                }
            }
            else if (actPrtcptn.getTypecode().equals(ParticipationType.SDLOC))
            {
                if (actPrtcptn.getRoleparticipation().getCode().code().equals(RoleCode.WORKGROUP.code()))
                {
                    Role r = (Role) actPrtcptn.getRoleParticipation();
                    Organization org = (Organization) r.getPlayerEntities();
                    // 科室名称
                    String workgroupName = org.getNameByUse(EntityNameUse.L).formatted().stringValue();
                    patientEncounterDTO.getInHospitalDTO().setDeptName(org.getNameByUse(EntityNameUse.L).formatted().stringValue());
                    patientEncounterDTO.getInHospitalDTO().setRoleID(r.getRoleId().toString());
                    patientEncounterDTO.getInHospitalDTO().setDepartmentId(r.getPlayerEntities().getEntityId().toString());
                    patientEncounterDTO.getInDepartment().setWorkgroupName(workgroupName);
                    continue;
                }
            }
        }

        StringBuilder jpql = new StringBuilder();
        jpql.append("select cd from RimCoreActCdSets cd left join cd.rimCoreActs act left join act.targetActRelationsList re left join re.sourceAct s where s.actId="
                + encounter.getActId() + " and cd.codingschemeEnName='Diagnosis'");
        @SuppressWarnings("unchecked")
        List<RimCoreActCdSets> cds = em.createQuery(jpql.toString()).getResultList();
        if (!cds.isEmpty())
        {
            DictionaryDTO dto = getDictionaryFactory().convertActCdSets(cds.get(0));
            patientEncounterDTO.setOutpat_diagose(dto);
            patientEncounterDTO.getInHospitalDTO().setOutPatDiagnose(dto);
        }

        Hl7NullRemover.removeHl7Null(patientEncounterDTO);
        return patientEncounterDTO;

    }


    public PatientEncounterDTO convertTransferAndInhospital(PatientEncounter transfer, PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {

        String encounterId = transfer.getId(ActIICode.PATIENTTRANSFER).clinicNo().stringValue();

        PatientEncounter inhospital = patientEncounterQuery.findLastInhosActByEncounterId(encounterId);
        if (inhospital != null)
        {
            patientEncounterDTO = convertPatientEncounterDTO(patientEncounterDTO, inhospital);
        }
        patientEncounterDTO = convertTransfer(transfer, patientEncounterDTO);
        return patientEncounterDTO;
    }


    // 组装转科dto
    @Override
    public PatientEncounterDTO convertTransfer(PatientEncounter transfer, PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {

        if (transfer == null)
        {
            log.info("AdmitManager-convertTransfer-转科动作为空！");
            return patientEncounterDTO;
        }

        // 就诊号
        patientEncounterDTO.setEncounterID(transfer.getId(ActIICode.PATIENTTRANSFER).clinicNo().stringValue());

        // 住院号

        // 转科时间
        patientEncounterDTO.getInHospitalDTO().setAdmissionTime(transfer.getActivityTime().hull().low().toDateString("yyyy-MM-dd HH:mm:ss"));

        for (ActParticipation actPrtcptn : transfer.getParticipations())
        {
            if (actPrtcptn.getTypecode().equals(ParticipationType.SBJ))
            {
                if (actPrtcptn.getRoleparticipation().getClassCode().equals(RoleClass.PAT))
                {
                    Patient patient = (Patient) actPrtcptn.getRoleparticipation();

                    // 患者信息
                    commonManager.convertByPatient(patientEncounterDTO, patient);
                    continue;
                }
            }
            // else if (actPrtcptn.getTypecode().equals(ParticipationType.ADM))
            // {
            // if
            // (actPrtcptn.getRoleparticipation().getClassCode().equals(RoleClass.EMP))
            // {
            // Employee emp = (Employee) actPrtcptn.getRoleparticipation();
            // Person p = (Person) emp.getPlayerEntities();
            // patientEncounterDTO.getLoginBaseInfo().setOperateName(p.getEntyNamesList().get(0).getFormatted());
            // patientEncounterDTO.getLoginBaseInfo().setOperateId(emp.getRoleIiList().get(0).getExtensionTxt());
            // continue;
            // }
            // }
            else if (actPrtcptn.getTypecode().equals(ParticipationType.ORG))
            {
                if (actPrtcptn.getRoleparticipation().getCode().code().equals(RoleCode.WORKGROUP.code()))
                {
                    Role r = (Role) actPrtcptn.getRoleparticipation();
                    Organization org = (Organization) r.getPlayerEntities();
                    // 科室名称
                    patientEncounterDTO.getTransferDTO().setFromWorkgroupName(org.getNameByUse(EntityNameUse.L).formatted().stringValue());

                    patientEncounterDTO.getInDepartment().setWorkgroupName(org.getNameByUse(EntityNameUse.L).formatted().stringValue());
                    patientEncounterDTO.getInHospitalDTO().setRoleID(r.getRoleId().toString());
                    patientEncounterDTO.getInHospitalDTO().setDepartmentId(r.getPlayerEntities().getEntityId().toString());
                    continue;
                }
            }
        }

        Hl7NullRemover.removeHl7Null(patientEncounterDTO);
        return patientEncounterDTO;

    }


    @Override
    // 组装PatientEncounterDTO
    public PatientEncounterDTO convertPatientEncounterDTO(PatientEncounter encounter) throws Hl7Exception
    {
        return convertPatientEncounterDTO(new PatientEncounterDTO(), encounter);

    }


    // 验证入院
    private ResultsDTO validateInHospital(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        ValidateUtilLocal util = (ValidateUtilLocal) Component.getInstance("ValidateUtil");
        if (StrUtil.isNotEmpty(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId())
                && !patientManager.isOutHospital(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId()))
        {
            log.info("AdmitManager-newInHospital()-不能重复住院！");
            return this.getResultsDTO(patientEncounterDTO.getPatientBaseInfoDTO().getNatureName() + "未出院，不能重复办理入院登记", true, false);
        }

        if (StrUtil.isEmpty(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId()))
        {

            if (!StrUtil.isEmpty(patientEncounterDTO.getCardId()))
            {
                if (patientQuery.validateEntityIIExsit(patientEncounterDTO.getCardId(), patientEncounterDTO.getCardTypeDic().getCodingschemeEnName(),
                    patientEncounterDTO.getCardTypeDic().getConceptCode()))
                {
                    return getResultsDTO("身份证号重复,请重新输入", true, false);
                }
            }
            if (!StrUtil.isEmpty(patientEncounterDTO.getInsuranceId()))
            {
                if (patientQuery.validateRoleIIExsit(patientEncounterDTO.getInsuranceId(), patientEncounterDTO.getInsuranceTypeDic()
                    .getCodingschemeEnName(), patientEncounterDTO.getInsuranceTypeDic().getConceptCode()))
                {
                    return getResultsDTO("医保号重复,请重新输入", true, false);
                }
            }
            if (!StrUtil.isEmpty(patientEncounterDTO.getInsuranceId()))
            {
                if (patientQuery.validateRoleIIExsit(patientEncounterDTO.getInsuranceId(), RoleIICode.ADMISSIONNO))
                {
                    return getResultsDTO("住院号重复,请重新输入", true, false);
                }
            }

        }

        ResultsDTO resultDTO = util.verifiedReturnResultsDTO(patientEncounterDTO, NewInHospital.class);
        if (resultDTO != null)
        {
            log.info(resultDTO.getResultDesc());
        }

        return resultDTO;

    }


    // 验证转科
    private ResultsDTO validatePatientTransfer(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {

        ResultsDTO resultDTO = validateUtil.verifiedReturnResultsDTO(patientEncounterDTO, NewDeptTransfer.class);
        if (resultDTO != null)
        {
            log.info(resultDTO.getResultDesc());
            return resultDTO;
        }

        // 上次活动的入科动作
        PatientEncounter lastIndepat = patientEncounterQuery.findLastAvtiveIndepartmentPatientEncounter(patientEncounterDTO.getPatientBaseInfoDTO()
            .getNatureId());

        if (lastIndepat == null)
        {
            log.info("AdmitManager-newDeptTransfer-找不到入科动作！");
            return getResultsDTO("找不到入科动作", true, false);
        }

        Role workgroup = patientQuery.findRoleByII((patientEncounterDTO.getTransferDTO().getToWorkgroupCode()), RoleIICode.DEPTCODE.toString());

        for (ActParticipation part : lastIndepat.getParticipations())
        {
            if (part.getTypecode().equals(ParticipationType.ELOC))
            {
                if (part.getRole().getScoperEntity().getEntityId().equals(workgroup.getPlayerEntity().getEntityId()))
                {
                    log.info("AdmitManager-newDeptTransfer-不能转入同一科室！");
                    return getResultsDTO("不能转入同一科室", true, false);
                }

            }
        }

        PatientEncounter transfer = patientEncounterQuery.findTransferPatientEncounter(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId());
        if (transfer != null)
        {
            log.info("AdmitManager-newDeptTransfer-不能重复转科！");
            return getResultsDTO("不能重复转科", true, false);
        }
        return null;
    }


    // 验证出院
    private ResultsDTO validateOutHospital(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {

        ResultsDTO resultDTO = validateUtil.verifiedReturnResultsDTO(patientEncounterDTO, NewOutHospital.class);
        if (resultDTO != null)
        {
            log.info(resultDTO.getResultDesc());
            return resultDTO;
        }

        PatientEncounter outHospital = patientEncounterQuery.findOutPatientEncounter(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId());
        if (outHospital != null)
        {
            log.info("AdmitManager-validateOutHospital-不能重复出院！");
            return getResultsDTO("不能重复出院", true, false);
        }
        return null;
    }


    // 组装转科动作
    private PatientEncounter constructPatientTransfer(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        // 转科
        CE code = this.getDataTypeFactory().newCE(ActCode.PATIENTTRANSFER.code().toString());

        // 转科act
        PatientEncounter patientEncounterAct = this.getActFactory().newPatientEncounter(ActMood.APT, code, null);

        // 设置就诊号
        patientEncounterAct.setId(commonManager.getEcounterIdForOther(patientEncounterDTO, ActCode.PATIENTTRANSFER));

        // 动作状态
        patientEncounterAct.setStatusCode(ActStatus.ACTIVE);

        // 转科时间 add by obama
        if (StrUtil.isNotEmpty(patientEncounterDTO.getTransferDTO().getAdmissionTime()))
        {

            Date date = DateUtil.getDateBy3String(patientEncounterDTO.getTransferDTO().getAdmissionTime());
            patientEncounterAct.setActivityTime(DataTypeUtil.getGTS(DataTypeUtil.getIVL_TS(date, date)));
        }
        else
        {
            Date date = new Date();
            patientEncounterAct.setActivityTime(DataTypeUtil.getGTS(DataTypeUtil.getIVL_TS(date, date)));
        }
        return patientEncounterAct;
    }


    // 组装入院动作
    private PatientEncounter constructInhospital(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {

        // code入院
        CE code = this.getDataTypeFactory().newCE(ActCode.HOSPITALIZED.code().stringValue());
        // 构建入院act
        PatientEncounter patientEncounter = this.getActFactory().newPatientEncounter(ActMood.APT, code, null);

        // 保存就诊号
        patientEncounter.setId(getEcounterIdForInhos(patientEncounterDTO));

        // 行为状态
        patientEncounter.setStatusCode(ActStatus.ACTIVE);

        // 入院目的
        if (StrUtil.isNotEmpty(patientEncounterDTO.getInHospitalDTO().getAdmissionPurpose()))
        {
            patientEncounter.setAdmissionPurpose(DataTypeUtil.getCE(patientEncounterDTO.getInHospitalDTO().getAdmissionPurpose()));
        }
        // 入院方式
        if (StrUtil.isNotEmpty(patientEncounterDTO.getInHospitalDTO().getAdmissionWay()))
        {
            patientEncounter.setAdmissionWay(DataTypeUtil.getCE(patientEncounterDTO.getInHospitalDTO().getAdmissionWay()));
        }
        // 联系人
        if (StrUtil.isNotEmpty(patientEncounterDTO.getInHospitalDTO().getLinkMan()))
        {
            patientEncounter.setPeLinkMan(DataTypeUtil.getST(patientEncounterDTO.getInHospitalDTO().getLinkMan()));
        }
        // 联系方式
        if (StrUtil.isNotEmpty(patientEncounterDTO.getInHospitalDTO().getLinkManWay()))
        {
            patientEncounter.setPeLinkManWay(DataTypeUtil.getST(patientEncounterDTO.getInHospitalDTO().getLinkManWay()));
        }
        // 联系人关系
        if (StrUtil.isNotEmpty(patientEncounterDTO.getInHospitalDTO().getLinkManRelation()))
        {
            patientEncounter.setPeLinkManRelation(DataTypeUtil.getST(patientEncounterDTO.getInHospitalDTO().getLinkManRelation()));
        }

        // 入院时间 add by obama
        if (StrUtil.isNotEmpty(patientEncounterDTO.getInHospitalDTO().getAdmissionTime()))
        {
            // patientEncounterAct.setCreationDate(DateUtil
            // .getTimestamp(patientEncounterDTO.getInHospitalDTO()
            // .getAdmissionTime()));
            Date date = DateUtil.getDateBy3String(patientEncounterDTO.getInHospitalDTO().getAdmissionTime());
            patientEncounter.setActivityTime(DataTypeUtil.getGTS(DataTypeUtil.getIVL_TS(date, date)));
        }
        else
        {
            Date date = new Date();
            patientEncounter.setActivityTime(DataTypeUtil.getGTS(DataTypeUtil.getIVL_TS(date, date)));
        }

        // 费别
        if (StrUtil.isNotEmpty(patientEncounterDTO.getChargeTypeDic().getConceptCode()))
        {
            CE dicCode = getDictionaryFactory().getCeByDictionaryDTO(patientEncounterDTO.getChargeTypeDic());

            patientEncounter.setChargeType(dicCode);
        }

        return patientEncounter;
    }


    // 组装出院动作
    private PatientEncounter constructOutHospital(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {

        CE code = this.getDataTypeFactory().newCE(ActCode.DISCHARGED.code().toString());

        PatientEncounter patientEncounterAct = this.getActFactory().newPatientEncounter(ActMood.EVN, code, null);

        patientEncounterAct.setId(commonManager.getEcounterIdForOther(patientEncounterDTO, ActCode.DISCHARGED));

        patientEncounterAct.setStatusCode(ActStatus.ACTIVE);

        // 出院方式
        patientEncounterAct
            .setLeaveHospitalWay(DictionaryFactory.getInstance().getCeByDictionaryDTO(patientEncounterDTO.getDischargedDTO().getOutWay()));
        // 出院时间
        Date date = DateUtil.getDateBy3String(patientEncounterDTO.getDischargedDTO().getOutTime());
        patientEncounterAct.setActivityTime(DataTypeUtil.getGTS(DataTypeUtil.getIVL_TS(date, date)));
        return patientEncounterAct;
    }


    // 住院生成就诊号
    private II getEcounterIdForInhos(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {

        String encounterId = "";
        if (!StrUtil.isEmpty(patientEncounterDTO.getEncounterID()))
        {
            encounterId = patientEncounterDTO.getEncounterID();
        }
        else
        {
            // 11位就诊号
            encounterId = DateUtil.getToday() + getSEQ_CLINICNO();
        }
        // 住院就诊号
        II regIi = DataTypeUtil.getII(root, DateUtil.getToday() + getEXTEN_CODE(), "true", ActCode.HOSPITALIZED.code().stringValue(), encounterId);
        return regIi;
    }


    // 设置住院号、住院次数.
    private void setInhosEncounterId(PatientEncounterDTO patientEncounterDTO, ActParticipation patientPart, Patient patient) throws Hl7Exception
    {
        // 住院号
        if (StrUtil.isEmpty(patientEncounterDTO.getHospitalizationNO()))
        {
            patientEncounterDTO.setHospitalizationNO(generalPtHospitalizationNO(patient));
        }
        if (patient.getId(RoleIICode.ADMISSIONNO) == null)
        {
            II hospitalizationNO = DataTypeUtil.getII(root, patientEncounterDTO.getHospitalizationNO(), RoleIICode.ADMISSIONNO.toString());
            patient.setId(hospitalizationNO);
        }

        // 住院次数
        if (!StrUtil.isEmpty(patientEncounterDTO.getInHospitalDTO().getEncounterNum()))
        {
            patientPart.setSequenceNumber(DataTypeUtil.getINT(Long.parseLong(patientEncounterDTO.getInHospitalDTO().getEncounterNum())));
        }
        else
        {
            String natureId = patient.getId(RoleIICode.PATIENTID).extension().stringValue();

            patientPart.setSequenceNum(patientEncounterQuery.findInhostNumByNatureId(natureId) + 1);

        }
    }


    // 构造转科动作参与
    private ResultsDTO constructTransferPart(PatientEncounterDTO patientEncounterDTO) throws Hl7Exception
    {
        // 患者
        Patient patient = patientQuery.findPatientByNeturalId(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId());
        if (patient == null)
        {
            log.info("转科患者为空");
            log.info("转科失败！");
            return this.getResultsDTO("转科失败", true, false);
        }
        ActParticipation patientPart = getActFactory().newActParticipation();
        patientPart.setTypeCode(ParticipationType.SBJ);
        addParticipation(patient, patientPart);

        // 转出科室
        Role fromWorkGroupRole = patientQuery
            .findRoleByII((patientEncounterDTO.getTransferDTO().getFromWorkgroupCode()), RoleIICode.DEPTCODE.toString());
        if (fromWorkGroupRole == null)
        {
            log.info("转出科室为空");
            log.info("转科失败！");
            return this.getResultsDTO("转科失败", true, false);
        }
        ActParticipation fromWorkpart = getActFactory().newActParticipation();
        fromWorkpart.setTypeCode(ParticipationType.ORG);
        addParticipation(fromWorkGroupRole, fromWorkpart);

        // 转入科室
        Role toWorkGroupRole = patientQuery.findRoleByII((patientEncounterDTO.getTransferDTO().getToWorkgroupCode()), RoleIICode.DEPTCODE.toString());
        if (toWorkGroupRole == null)
        {
            log.info("转入科室为空");
            log.info("转科失败！");
            return this.getResultsDTO("转科失败", true, false);
        }
        ActParticipation toWorkpart = getActFactory().newActParticipation();
        toWorkpart.setTypeCode(ParticipationType.SDLOC);
        addParticipation(toWorkGroupRole, toWorkpart);

        // 员工角色
        Employee empRole = employeeQuery.findEmployeeByCode(patientEncounterDTO.getLoginBaseInfo().getOperateId());
        if (empRole == null)
        {
            empRole = employeeQuery.findEmployeeByCode("12345");
            log.info("操作员为空,使用默认操作员");
        }
        else
        {
            log.info("成功得到操作员角色！");
        }
        ActParticipation empPart = getActFactory().newActParticipation();
        empPart.setTypeCode(ParticipationType.ADM);
        addParticipation(empRole, empPart);
        return null;
    }

    @Override
    public PatientEncounterDTO convertOutPatientEncounterDTOFromPatientEncounter(PatientEncounter pe, PatientEncounterDTO peDTO) throws Hl7Exception
    {
        DischargedDTO dischargedDTO = peDTO.getDischargedDTO();
        dischargedDTO.setOutTime(pe.getActivityTime().hull().low().toDateString("yyyy-MM-dd HH:mm:ss"));
        if (ListUtil.isNotEmpty(pe.getParticipations()))
        {
            for (ActParticipation p : pe.getParticipations())
            {
                if( p.getRole().getCode().code().equals(ActCode.WORKGROUP.code()))
                {
                    dischargedDTO.setWorkGroupName(p.getRole().getPlayerEntity().getNameByUse(EntityNameUse.L).formatted().literal().stringValue());    
                }
            }
        }
        DictionaryDTO diagnosisName = getMainDiagnosis(peDTO.getPatientBaseInfoDTO().getPersonId(),peDTO.getInHospitalDTO().getEncounterNum());
        dischargedDTO.setDiagnosisName(diagnosisName);
        return peDTO;
    }

    @SuppressWarnings("unchecked")
    private DictionaryDTO getMainDiagnosis(String patientRoleId,String encounterNum ) throws Hl7Exception{
        InpatientRecordsManagerLocal inpatientRecordsManager = (InpatientRecordsManagerLocal) Component.getInstance("InpatientRecordsManager");
        ResultsDTO outRecordDTO = inpatientRecordsManager.findDiagnosisListByPatientId(patientRoleId,encounterNum);
        List<EmrDiagnosisDTO> edsList = (List<EmrDiagnosisDTO>)outRecordDTO.getObject();
        if( ListUtil.isNotEmpty(edsList)){
            for( EmrDiagnosisDTO eds: edsList)
            {
                System.out.println( eds.getDiagnosisType());
                System.out.println( eds.getDiagnosisName());
                System.out.println( eds.getMasterDiagnosticsFlag() );
            }
        }
        return new DictionaryDTO();
    }
}
